// @/components/knowledge-base/utils/api-utils.js
export const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export const apiCallWithRetry = async (
  apiCall,
  maxRetries = 3,
  initialDelay = 1000
) => {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await apiCall();
    } catch (error) {
      const isRateLimitError =
        error.message?.includes("429") ||
        error.message?.includes("Rate limit") ||
        (error.response && error.response.status === 429);

      if (isRateLimitError && attempt < maxRetries) {
        const delayTime = initialDelay * Math.pow(2, attempt - 1);
        console.log(
          `速率限制触发，等待 ${delayTime}ms 后重试... (尝试 ${attempt}/${maxRetries})`
        );
        await delay(delayTime);
        continue;
      }
      throw error;
    }
  }
};